package com.example.day02;

import android.os.Bundle;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.example.day02.fragment.HomeFragment;
import com.example.day02.fragment.MyFragment;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    private LinearLayout mContent;
    private TabLayout mTab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        //做一个线性布局  用fragment替换展示fragment
        mContent = (LinearLayout) findViewById(R.id.content);
        mTab = (TabLayout) findViewById(R.id.tab);

        final HomeFragment homeFragment = new HomeFragment();
        final MyFragment myFragment = new MyFragment();

        getSupportFragmentManager()//获得fragment管理器
                .beginTransaction()//开启一个事物
                .add(R.id.content, homeFragment)//添加
                .add(R.id.content, myFragment)//添加
//                .show(homeFragment)//show
//                .hide(homeFragment)//隐藏
                .commit();//提交事务

        mTab.addTab(mTab.newTab().setText("主页"));
        mTab.addTab(mTab.newTab().setText("我的"));
        //tablayout 添加选择监听
        mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {//选中tablayout监听
                switch (tab.getPosition()) {
                    case 0:
                        getSupportFragmentManager()
                                .beginTransaction()
                                .show(homeFragment)
                                .hide(myFragment)
                                .commit();
                        break;
                    case 1:
                        getSupportFragmentManager()
                                .beginTransaction()
                                .show(myFragment)
                                .hide(homeFragment)
                                .commit();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {//未选中监听

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {//再次选中

            }
        });
    }
}
